﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TyNetCoreBlog.Helpers
{
    /// <summary>
    /// 分页列表类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class PagedList<T> : List<T>
    {
        public int CurrentPage { get; private set; }    //当前页
        public int PageSize { get; private set; }    //页大小
        public int TotalPages { get; private set; }    //总页数
        public int TotalCount { get; private set; }    //总条数
        public bool HasPrevious => CurrentPage > 1;    //是否有前一页
        public bool HasNext => CurrentPage < TotalPages;    //是否有下一页

        public PagedList(List<T> items, int totalCount, int pageNum, int pageSize)
        {
            TotalCount = totalCount;
            CurrentPage = pageNum;
            PageSize = pageSize;
            TotalPages = (int)Math.Ceiling((double)totalCount / PageSize);
            AddRange(items);
        }


        /// <summary>
        /// 创建PagedList<T>的静态方法
        /// </summary>
        /// <param name="source"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static async Task<PagedList<T>> CreateAsync(IQueryable<T> source, int pageNum, int pageSize)
        {
            var totalCount = source.Count();
            var items = source.Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
            var plist = new PagedList<T>(items,totalCount, pageNum, pageSize);
            return await Task.FromResult(plist);
        }
    }
}
